import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

public class Opencv {

    public static void main(String[] args) throws InterruptedException, IOException {

        // 加载动态库
        URL url = ClassLoader.getSystemResource("opencv_java452.dll");
        System.load(url.getPath());

        Mat imread = Imgcodecs.imread("C:\\Users\\Administrator\\Desktop\\test.jpg");
        int height = imread.height();
        int width = imread.width();
        System.out.println(width + " :: " + height);

        System.out.println(fileToByte(new File("C:\\Users\\Administrator\\Desktop\\test.jpg")).length);
        byte[] bytes = matToByteArray(imread);
        System.out.println(bytes.length);
        Mat clone = imread.clone();
        HighGui.imshow("原图", clone);

        // https://blog.csdn.net/qianlixiaomage/article/details/108416400
        // opencv基础：https://blog.csdn.net/qq_18604209/article/details/104029689
        // https://www.cnblogs.com/think-in-java/p/5527389.html
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) (255 - bytes[i]&0xff);
        }
        imread.put(0, 0, bytes);
        HighGui.imshow("修改图", imread);

        Scalar color = new Scalar(0, 0, 255);
        Object[] objects = new Object[]{513, 1546, 641, 1638};
        for (int i = 0; i < objects.length; i = i + 4) {
            Point point = new Point(Double.parseDouble(objects[i + 1].toString()), Double.parseDouble(objects[i].toString()));
            Point point1 = new Point(Double.parseDouble(objects[i + 3].toString()), Double.parseDouble(objects[i + 2].toString()));
            Imgproc.rectangle(clone, point, point1, color);
        }
        HighGui.imshow("绘图", clone);
        HighGui.waitKey();
    }

    public static byte[] matToByteArray(Mat mat) {
        byte[] bytes = new byte[mat.cols() * mat.rows() * mat.channels()];
        mat.get(0, 0, bytes);
        return bytes;
    }

    public static byte[] fileToByte(File img) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedImage bi;
        bi = ImageIO.read(img);
        ImageIO.write(bi, "jpg", baos);
        return baos.toByteArray();
    }
}
